# -*- coding: utf-8 -*-
# @Time : 2021/3/11 17:59 
# @Author : for 
# @File : mytags.py 
# @Motto: good good study,day day up


# TODO  统计各个分类和标签下的文章数
#  https://blog.csdn.net/fanxindong0620/article/details/103749454

from django import template
from blog.models import Blog, Category, Tags, Contact
from django.db.models.aggregates import Count
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

register = template.Library()


@register.simple_tag()
def count_blog():
    return Blog.objects.all().count()


@register.simple_tag()
def count_tags():
    return Tags.objects.all().count()


@register.simple_tag()
def count_types():
    return Category.objects.all().count()


@register.simple_tag()
def get_email():
    return Contact.objects.all()[0].email


@register.simple_tag()
def get_qq():
    return Contact.objects.all()[0].qq


@register.simple_tag()
def get_introduce():
    return Contact.objects.all()[0].introduce


@register.inclusion_tag('blog/inclusions/index/_categories.html', takes_context=True)
def show_categories(context):
    category_list = Category.objects.annotate(num_posts=Count('blog')).filter(num_posts__gt=0)
    return {
        'category_list': category_list,
    }


@register.inclusion_tag('blog/inclusions/index/_recent_posts.html', takes_context=True)
def show_recent_posts(context, num=5):
    return {
        'recent_post_list': Blog.objects.filter(is_recommend=True)[:num],
    }


@register.inclusion_tag('blog/inclusions/index/_tags.html', takes_context=True)
def show_tags(context):
    tag_list = Tags.objects.annotate(num_posts=Count('blog')).filter(num_posts__gt=0)
    return {
        'tag_list': tag_list,
    }


@register.inclusion_tag('blog/inclusions/index/_blog.html', takes_context=True)
def show_new_blog(context):
    blogs = Blog.objects.order_by('-created')[:3]
    return {
        'blogs': blogs
    }


@register.inclusion_tag('blog/inclusions/tag/_tags.html', takes_context=True)
def show_all_tags(context):
    tag_list = Tags.objects.annotate(num_posts=Count('blog')).filter(num_posts__gt=0)
    return {
        'tag_list': tag_list,
    }


@register.inclusion_tag('blog/inclusions/types/_types.html', takes_context=True)
def show_all_types(context):
    type_list = Category.objects.annotate(num_posts=Count('blog')).filter(num_posts__gt=0)
    return {
        'type_list': type_list,
    }


@register.inclusion_tag('blog/_archives.html', takes_context=True)
def show_archives(context):
    return {
        'date_list': Blog.objects.dates('created', 'month', order='DESC'),
        # 'blog_list': Blog.objects.order_by('-created'),
        # 把ArchivesView视图中的page_obj数据传入到page_obj模板标签中
        'page_obj': context['page_obj']
    }
